<script setup>
import Toast from "@vant/weapp/dist/toast/toast";
import myCanvas from "@/utils/myCanvas";

import { ref, nextTick, computed } from 'vue';
import { onLoad, onReady } from '@dcloudio/uni-app';



// 页面传递参数
const queryItem = ref({})

let imgCanvas, eraseCanvas



// canvas尺寸
const canvasBoxRect = ref({})
// 图片绘制信息
const imgRect = ref({})
// 原图尺寸信息
const oldImgSize = ref({})


// 绘图历史
const history = ref([]);
const historyIndex = ref(-1);

// 是否是工作台
const isWorkbench = ref(false);
// 橡皮擦/线条大小
const sliderValue = ref(30)

// 是否擦除中
const isDrawing = ref(false);

// 记录上一个点
const lastPoint = ref({});
// 橡皮擦位置
const eraserPosition = ref({ x: 0, y: 0 });


// 是否可以上一步
const lastStep = computed(() => historyIndex.value > 0);

// 是否可以下一步
const nextStep = computed(() => historyIndex.value < history.value.length - 1);

// 返回上一页
function backFn() {
    let pages = getCurrentPages()
    let prevPage = pages[pages.length - 2]
    uni.navigateBack({
        success() {
            prevPage.$vm.uploadImgFn()
        }
    })
}

// 返回上一页并切换tab
function switchType() {
    let pages = getCurrentPages()
    let prevPage = pages[pages.length - 2]
    prevPage.$vm.tabsChange(1)
    uni.navigateBack()
}



// 保存图片到相册
function saveImageFn() {
    uni.saveImageToPhotosAlbum({
        filePath: history.value[historyIndex.value],
        success() {
            Toast.success('保存成功')
        },
    })
}


// 调整橡皮擦线条大小
function sliderChange(e) {
    sliderValue.value = e.detail
}

// 调整橡皮擦线条大小
function sliderDrag(e) {
    sliderValue.value = e.detail.value
}


// 手指抬起
function touchend() {
    if (!isDrawing.value) return
    isDrawing.value = false;
    eraseCanvas.clearRect(0, 0, canvasBoxRect.value.width, canvasBoxRect.value.height)
    exportCanvas();
}


// 触摸移动
function touchmove(e) {
    if (!isDrawing.value) return
    const newPoint = e.touches[0]; // 记录当前点
    imgCanvas.smoothErase(lastPoint.value.x, lastPoint.value.y, newPoint.x, newPoint.y, sliderValue.value)
    eraseCanvas.clearRect(0, 0, canvasBoxRect.value.width, canvasBoxRect.value.height)
    eraseCanvas.drawRoundedRect(newPoint.x, newPoint.y, sliderValue.value, sliderValue.value / 2, 'rgba(0,0,0,0.5)')
    lastPoint.value = newPoint; // 更新上一个点
}

// 手指按下
function touchstart(e) {
    if (!queryItem.value.imgPath || !isWorkbench.value) return
    isDrawing.value = true;
    lastPoint.value = e.touches[0]; // 记录起点
    eraserPosition.value = {
        x: e.touches[0].x,
        y: e.touches[0].y
    }
}





// 清除历史记录
function clearHistory() {
    if (history.value.length > 0) {
        history.value = [history.value[0]]; // 保留初次绘图历史
        historyIndex.value = 0;
    } else {
        history.value = [];
        historyIndex.value = -1;
    }
    if (history.value.length > 0) {
        restoreCanvas(history.value[0]); // 恢复初次绘图
    }
    isWorkbench.value = false; // 退出工作台模式
}


// 上一步
function undo() {
    if (historyIndex.value > 0) {
        historyIndex.value--;
        restoreCanvas(history.value[historyIndex.value]);
    }
}

// 下一步
function redo() {
    if (historyIndex.value < history.value.length - 1) {
        historyIndex.value++;
        restoreCanvas(history.value[historyIndex.value]);
    }
}


// 恢复画布
function restoreCanvas(imagePath) {
    imgCanvas.drawImage(imagePath, imgRect.value.dx, imgRect.value.dy, imgRect.value.width, imgRect.value.height,
        () => {
            imgCanvas.clearRect(0, 0, canvasBoxRect.value.width, canvasBoxRect.value.height); // 清空画布
        })
}

// 图片绘制
function loadDrawImageFn() {
    imgRect.value.dx = (canvasBoxRect.value.width - imgRect.value.width) / 2;
    imgRect.value.dy = (canvasBoxRect.value.height - imgRect.value.height) / 2;

    imgCanvas.drawImage(queryItem.value.imgPath, imgRect.value.dx, imgRect.value.dy, imgRect.value.width, imgRect.value.height,
        () => {
            imgCanvas.clearRect(0, 0, canvasBoxRect.value.width, canvasBoxRect.value.height)
            imgCanvas.drawRect(imgRect.value.dx, imgRect.value.dy, imgRect.value.width, imgRect.value.height, 'transparent')
            imgCanvas.ctx.save()
            imgCanvas.ctx.clip()
        },
        () => {
            imgCanvas.ctx.restore()
            Toast.clear()
            exportCanvas()
        },
    )
}

// 导出当前画布为图片并存入历史记录
function exportCanvas() {
    uni.canvasToTempFilePath({
        canvas: imgCanvas.canvas,
        x: imgRect.value.dx,
        y: imgRect.value.dy,
        width: imgRect.value.width,
        height: imgRect.value.height,
        destWidth: oldImgSize.value.width,
        destHeight: oldImgSize.value.height,
        success: (res) => {
            // 如果有未来的历史记录，清除它们
            if (historyIndex.value < history.value.length - 1) {
                history.value.splice(historyIndex.value + 1);
            }
            uni.getImageInfo({
                src: res.tempFilePath,
                success: (res) => {
                    history.value.push(res.path);
                    historyIndex.value++;
                }
            })
        }
    });
}



// 计算图片宽高比及外部边框盒子的宽高
async function calculatePicAspectRatio(path) {
    const { width, height } = await uni.getImageInfo({ src: path })

    const widthRatio = canvasBoxRect.value.width / width;
    const heightRatio = canvasBoxRect.value.height / height;
    const scaleRatio = Math.min(widthRatio, heightRatio);

    // 计算缩放后的图片宽度和高度
    const scaledWidth = width * scaleRatio;
    const scaledHeight = height * scaleRatio;

    // 原始图片尺寸
    oldImgSize.value = {
        width,
        height
    }

    imgRect.value = {
        width: scaledWidth,
        height: scaledHeight
    }
}



onReady(() => {
    uni.createSelectorQuery().select('.canvas_box').boundingClientRect((res) => {
        canvasBoxRect.value.width = res.width
        canvasBoxRect.value.height = res.height
        imgCanvas = new myCanvas('imgCanvas')
        eraseCanvas = new myCanvas('eraseCanvas')
        calculatePicAspectRatio(queryItem.value.imgPath).then(() => {
            loadDrawImageFn()
        })
    }).exec()
})

onLoad((e) => {
    Toast.loading({
        message: '图片加载中...',
        duration: 0,
        forbidClick: true,
    })

    if (e.data) {
        queryItem.value = JSON.parse(e.data)
    }
})
</script>

<template>
    <div class='imgMattingDetail'>
        <NavBar>{{ queryItem?.title }}</NavBar>
        <div class="container">
            <div class="canvas_box">
                <canvas type="2d" id="imgCanvas" class="imgCanvas"></canvas>
                <canvas type="2d" id="eraseCanvas" class="eraseCanvas" @touchstart="touchstart" @touchmove.stop="touchmove"
                    @touchend="touchend"></canvas>
            </div>
        </div>
        <div class="footer">
            <div class="footer_placeholder"></div>
            <div class="footer_content">
                <div class="saveImage_box" v-if="!isWorkbench">
                    <div class="left" @click="isWorkbench = true">
                        <i class="iconfont ai-icon-xiangpica1"></i>
                        <div>橡皮擦</div>
                    </div>
                    <div class="left_btn" @click="backFn">继续上传</div>
                    <div class="right">
                        <div class="create_btn" @click="saveImageFn">
                            <div class="create_btn_title">保存图片</div>
                        </div>
                        <div class="draw_label" @click="switchType">不满意，试试选择类型抠图</div>

                    </div>
                </div>
                <div class="eraser_box" v-else>
                    <div class="eraser_top">
                        <div class="left" @click="clearHistory">
                            <i class="iconfont ai-icon-a-shibieleixingguanbi"></i>
                        </div>
                        <div class="center">
                            <i class="iconfont ai-icon-shangyibu" :class="{ active: lastStep }" @click="undo"></i>
                            <i class="iconfont ai-icon-xiayibu" :class="{ active: nextStep }" @click="redo"></i>

                        </div>
                        <div class="right" @click="isWorkbench = false">
                            <i class="iconfont ai-icon-a-shibieleixingqueren"></i>
                        </div>
                    </div>

                    <div class="eraser_center">
                        <div class="erase">橡皮大小</div>
                        <div class="slider_box">
                            <van-slider :value="sliderValue" :min="15" :max="45" @drag="sliderDrag" @change="sliderChange"
                                bar-height="8px" active-color="#83CD88" />
                            <div class="slider_label">涂抹图片中不想要的部分即可</div>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>
    <van-toast id="van-toast" />
</template>

<style lang='scss' scoped>
.imgMattingDetail {
    height: 100vh;
    display: flex;
    flex-direction: column;

    .container {
        flex: 1;
        padding: 30rpx;

        .canvas_box {
            position: relative;
            height: 100%;
            background: var(--a-main-box-bg-color);
            border-radius: 20rpx;

            .imgCanvas,
            .eraseCanvas {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;

                &.imgCanvas {
                    z-index: 1;
                }

                &.eraseCanvas {
                    z-index: 2;
                }
            }
        }
    }

    .footer {
        .footer_placeholder {
            height: 400rpx;
        }

        .footer_content {
            box-sizing: border-box;
            position: fixed;
            left: 0;
            bottom: 0;
            width: 100%;
            height: 400rpx;
            background: var(--a-main-tabNav-bg-color);
            padding: 30rpx;

            .saveImage_box {
                display: flex;
                align-items: center;
                gap: 30rpx;

                .left {
                    flex-shrink: 0;
                    color: var(--a-one-text-color);
                    text-align: center;
                    font-size: 22rpx;
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    justify-content: center;
                    gap: 5rpx;

                    .iconfont {
                        font-size: 42rpx;
                    }
                }

                .left_btn {
                    box-sizing: border-box;
                    width: 200rpx;
                    height: 86rpx;
                    border-radius: 42rpx;
                    color: var(--a-main-color);
                    font-size: 32rpx;
                    border: 2rpx solid var(--a-main-color);

                    display: flex;
                    align-items: center;
                    justify-content: center;
                }

                .right {
                    flex: 1;
                    position: relative;

                    .create_btn {
                        height: 86rpx;
                        background: var(--a-main-color);
                        border-radius: 44rpx;
                        display: flex;
                        flex-direction: column;
                        align-items: center;
                        justify-content: center;

                        .create_btn_title {
                            font-size: 32rpx;
                            color: var(--a-one-text-color);
                        }

                        .create_btn_label {
                            font-size: 20rpx;
                            color: var(--a-one-text-color);
                        }
                    }

                    .draw_label {
                        font-size: 24rpx;
                        color: var(--a-two-text-color);
                        position: absolute;
                        top: 140rpx;
                        left: 0;
                        width: 100%;
                        text-align: center;
                    }
                }
            }

            .eraser_box {
                .eraser_top {
                    display: flex;
                    align-items: center;

                    .left,
                    .right {
                        flex-shrink: 0;
                        color: var(--a-one-text-color);

                        .iconfont {
                            font-size: 42rpx;
                        }
                    }

                    .center {
                        flex: 1;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        gap: 98rpx;



                        .iconfont {
                            font-size: 56rpx;
                            color: #8a8a8a;

                            &.active {
                                color: var(--a-one-text-color);

                            }
                        }
                    }
                }

                .eraser_center {
                    display: flex;
                    align-items: center;
                    gap: 32rpx;
                    font-size: 26rpx;
                    color: var(--a-three-text-color);
                    margin-top: 40rpx;

                    .erase {
                        flex-shrink: 0;
                    }

                    .slider_box {
                        position: relative;
                        flex: 1;

                        .slider_label {
                            font-size: 24rpx;
                            color: var(--a-two-text-color);
                            position: absolute;
                            top: 50rpx;
                            left: 0;
                            width: 100%;
                            text-align: center;
                        }
                    }
                }

            }
        }
    }
}
</style>